#/bin/bash
############################
# 直接启动
# mongod --config ${INSTALL_DIR}/mongodb/etc/mongodb.conf  关闭服务
# mongod --config ${INSTALL_DIR}/mongodb/etc/mongodb.conf --shutdown  启动服务
# 配置开机启动后的启动方式
# service mongod start|stop|restart|status
######
# 查看开启的端口号
# iptables -L -n
# 查看端口使用情况
# lsof -i:27017
# 查看linxu的位数
# getconf LONG_BIT
############################
RESOURCE_FOLDER="mongodb-linux-x86_64-4.0.9"
RESOURCE_URL="https://fastdl.mongodb.org/linux/${RESOURCE_FOLDER}.tgz"  #资源路径
DOWNLOAD_DIR="/home/tools" # 下载的目录
LOG_FILE="${DOWNLOAD_DIR}/installMongoDB.log" 
INSTALL_DIR="/usr/local"
PORT="27017"

rpm -q wget &>/dev/null
if [ $? -ne 0 ]; then
    yum -y install make wget
fi

if [ ! -d "${DOWNLOAD_DIR}" ]; then
    mkdir $DOWNLOAD_DIR -p
fi
if [ ! -d "${INSTALL_DIR}" ]; then
    mkdir $INSTALL_DIR -p
fi

##### 安装MongoDB
# 下载资源
cd ${DOWNLOAD_DIR}
if [ ! -f "${RESOURCE_FOLDER}.tgz" ]; then
    echo $(date +"%Y-%m-%d %H:%M:%S") ":开始下载资源文件;" >>${LOG_FILE}
    wget -c $RESOURCE_URL
fi
# 如果源文件存在，
if [ -f "${RESOURCE_FOLDER}.tgz" ]; then
    #则检测是否已解压
    if [ ! -d "${RESOURCE_FOLDER}" ]; then
        tar -zxvf ${RESOURCE_FOLDER}.tgz
    fi
fi
# 改名，放到目录 ${INSTALL_DIR},如:/usr/local
mv ${RESOURCE_FOLDER} ${INSTALL_DIR}/mongodb
# 新建必要的文件夹（依次是：数据库 日志 配置文件）
cd ${INSTALL_DIR}/mongodb
if [ ! -d "data" ]; then
    mkdir data
fi
if [ ! -d "log" ]; then
    mkdir log
fi
if [ ! -d "etc" ]; then
    mkdir etc
fi
# 添加系统路径
grep "${INSTALL_DIR}/mongodb/bin" /etc/profile > /dev/null
if [ $? -ne 0 ]; then
    sed -i '$a export PATH=$PATH:'"${INSTALL_DIR}"'/mongodb/bin' /etc/profile
    source /etc/profile
fi

# 换种方式和添加系统路径二选一
## ln -s ${INSTALL_DIR}/mongodb/bin/mongo /usr/bin/mongo

##### 配置文件
# 不存在配置文件就创建配置文件
if [ ! -f "${INSTALL_DIR}/mongodb/etc/mongodb.conf" ]; then
cat>${INSTALL_DIR}/mongodb/etc/mongodb.conf <<END
# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

processManagement:
   fork: true
net:
   bindIp: localhost #localhost即为127.0.0.1,使用0.0.0.0是任意可以外网访问
   port: ${PORT} #默认使用的端口号,可按实际情况处理
storage:
   dbPath: ${INSTALL_DIR}/mongodb/data
   journal:
      enabled: true
systemLog:
   destination: file
   path: "${INSTALL_DIR}/mongodb/log/mongod.log"
   logAppend: true
security:
   authorization: enabled
#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

END
fi

##### 配置开机启动

if [ ! -f "/etc/rc.d/init.d/mongod" ]; then
cat>/etc/rc.d/init.d/mongod <<END
start() {  
${INSTALL_DIR}/mongodb/bin/mongod --config ${INSTALL_DIR}/mongodb/etc/mongodb.conf
}  
stop() {  
${INSTALL_DIR}/mongodb/bin/mongod --config ${INSTALL_DIR}/mongodb/etc/mongodb.conf --shutdown
}  
status()
{
        a=\`ps aux|grep '${INSTALL_DIR}/mongodb' | grep -v 'grep' | grep ${INSTALL_DIR}/mongodb/etc/mongodb.conf  | awk '{print \$2}'\`
        if [ "\$a" != "" ];then
            echo "当前MongoDB已启动, 进程号为: \$a"
        else 
            echo "当前MongoDB未启动"
        fi
}
case "\$1" in  
  start)  
 start  
 ;;  
stop)  
 stop  
 ;;  
restart)  
 stop  
 start  
 ;;  
status)  
 status  
 ;;  
  *)  
  echo "Usage: /etc/rc.d/init.d/mongod {start|stop|restart|status}" >&2
  exit 3
 ;; 
esac
END
chmod +x /etc/rc.d/init.d/mongod
fi

## 开启防火墙的端口
openPort () {
        if [ ! $1 ]; then
                echo '请输入需要开启的端口，请检查'
                exit 1
        fi
        TYPE="tcp"
        if [ $2 ]; then
               TYPE="$2"
        fi
        portStatus=$(firewall-cmd --query-port="$1"/"${TYPE}")
        if [ $portStatus = 'no' ]; then
                sudo firewall-cmd --add-port=$1/${TYPE} --permanent
                firewall-cmd --reload
                sleep 1s
                echo "端口【$1/${TYPE}】已成功开启"
        else 
                echo "端口【$1/${TYPE}】已开启，无需重复开启"
        fi
}
Firewalld=`systemctl status firewalld | grep Active  | awk '{print $3}' | awk -F '[)(]' '{print $2}'`
if [ $Firewalld == running ];then
	openPort ${PORT}
else
   sudo systemctl start firewalld
   if [ $? -eq 0 ]; then
       openPort ${PORT}
       echo "开启防火墙成功-开启端口成功" >>${LOG_FILE}
    else
        echo "开启防火墙失败-开启端口失败" >>${LOG_FILE}
        exit 1
    fi
   sudo systemctl stop firewalld
   if [ $? -eq 0 ]; then
      echo "防火墙保留关闭的状态" >>${LOG_FILE}
      exit 1
    fi
fi


